import { loginApi } from '@/api/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import request from '@/utils/request'

const getDefaultState = () => {
  return {
    token: getToken()[0],
    isRefreshing: false,
    userInfo: {
      userId: '',
      loginAccount: '',
      phone: '',
      email: '',
      ban: '',
      registerTime: '',
      nickname: '',
      gender: '',
      birthday: '',
      roles: []
    }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ISREFRESHING: (state, isRefreshing) => {
    state.isRefreshing = isRefreshing
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { loginAccount, password, type } = userInfo
    return new Promise((resolve, reject) => {
      request(loginApi.login, { loginAccount: loginAccount.trim(), password, type })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 通过钉钉登录
  loginByDingTalk({ commit }, code) {
    return new Promise((resolve, reject) => {
      request(loginApi.loginByDingTalk, { code })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 通过手机验证码登录
  loginByPhone({ commit }, phoneLoginForm) {
    return new Promise((resolve, reject) => {
      request(loginApi.loginByPhone, { ...phoneLoginForm })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  //刷新会话
  sessionRefresh({ commit }) {
    commit('SET_ISREFRESHING', true)
    return new Promise((resolve, reject) => {
      request(loginApi.sessionRefresh, { refreshToken: getToken()[1], userId: getToken()[2] })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
          commit('SET_ISREFRESHING', false)
          resolve()
        })
        .catch((error) => {
          commit('SET_ISREFRESHING', false)
          reject(error)
        })
    })
  },
  // 通过邮箱验证码登录
  loginByEmail({ commit }, emailLoginForm) {
    return new Promise((resolve, reject) => {
      request(loginApi.loginByEmailCode, { ...emailLoginForm })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 通过工号
  loginByStaffNum({ commit }, staffNumLoginForm) {
    return new Promise((resolve, reject) => {
      request(loginApi.loginByStaffNum, { ...staffNumLoginForm })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 通过微信登录
  loginByWeChat({ commit }, code) {
    return new Promise((resolve, reject) => {
      request(loginApi.loginByWechat, { code })
        .then((response) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token, data.refreshToken, data.userId, new Date().getTime() + 28 * 60 * 1000)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      request(loginApi.getInfo)
        .then((response) => {
          const { data } = response
          if (!data) {
            reject('验证失败，请重新登录')
          }
          data.roles = ['admin']
          if (!data.roles || data.roles.length <= 0) {
            reject('getInfo: 角色数据必须是一个非空数组！')
          }
          commit('SET_USERINFO', data)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      request(loginApi.logout, { token: state.token })
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
